Skip to main content

217. Contains Duplicate

Question

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Example 1:

Input: nums = [1,2,3,1]
Output: true

Example 2:

Input: nums = [1,2,3,1]
Output: true

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

Constraints:

- 1 <= nums.length <= 105
- -109 <= nums[i] <= 109

Approach

  1. Create a hash table with unordered_map with both key and value as integer. The key will be the element from nums, while value will be the number of occurences.
  2. Iterate through the nums vector, for every element, insert into the table and at the same time increment the count.
  3. As long as the count is > 1, it is a duplicate.

Solution

class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
//hash map
unordered_map<int,int> m;

for(int i = 0; i < nums.size(); i++){
//insert into map, in the position of current element
//increment count
m[nums[i]]++;

//when the element has more than 1 as value, it is a duplicate
if(m[nums[i]] > 1) return true;
}

return false;
}
};